/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.superduperbudget.central.ws.user;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.ws.rs.DELETE;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import se.superduperbudget.central.core.EMF;
import se.superduperbudget.central.db.SuperDuperTag;
import se.superduperbudget.central.db.SuperDuperTransaction;

/**
 * REST Web Service
 *
 * @author Emil
 */
@Path("/user/tagging")
public class Tagging {
    @Context
    private UriInfo context;

    /** Creates a new instance of Login */
    public Tagging() {
    }
    
    @POST
    @Path("{transId}/{tagId}")
    public void tag(@PathParam("transId") int transactionId, @PathParam("tagId") int tagId) {
        EntityManager em = EMF.get().createEntityManager();
        
        SuperDuperTransaction trans = em.find(SuperDuperTransaction.class, transactionId);
        SuperDuperTag tag = em.find(SuperDuperTag.class, tagId);
        
        trans.getTags().add(tag);
        
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.merge(tag);
        tx.commit();
        
        em.close();
    }
    
    @DELETE
    @Path("{transId}/{tagId}")
    public void untag(@PathParam("transId") int transactionId, @PathParam("tagId") int tagId) {
        EntityManager em = EMF.get().createEntityManager();
        
        SuperDuperTransaction trans = em.find(SuperDuperTransaction.class, transactionId);
        SuperDuperTag tag = em.find(SuperDuperTag.class, tagId);
        
        trans.getTags().remove(tag);
        
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.merge(tag);
        tx.commit();
        
        em.close();
    }
}
